package com.example.developerlab;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

public class PicUtils {
	private static final String TAG = PicUtils.class.getSimpleName();

	public static void downloadPic(Activity activity, String picUrl, ImageView backgroundPic, PicCallback callback) {
		if (!TextUtils.isEmpty(picUrl)) {
			// 如果有配置图片,则展示否则不展示
			try {
				Glide.with(activity)
						.asDrawable()
						.load(picUrl)
						.listener(new RequestListener<Drawable>() {
							@Override
							public boolean onLoadFailed(@Nullable GlideException e, Object model,
														Target<Drawable> target,
														boolean isFirstResource) {
								Log.d(TAG, "onLoadFailed url=" + picUrl);
								return false;
							}

							@Override
							public boolean onResourceReady(Drawable resource, Object model,
														   Target<Drawable> target,
														   DataSource dataSource,
														   boolean isFirstResource) {
								Log.d(TAG, "onResourceReady url=" + picUrl);
								if (callback != null) {
									callback.onSuccess();
								}
								return false;
							}
						})
						.apply(new RequestOptions().fitCenter())
						.into(backgroundPic);
			} catch (Exception e) {
			}
		}
	}

	public interface PicCallback {
		void onSuccess();
	}
}
